<template>
  <div v-if="visible" class="countdown-overlay">
    <div class="countdown-dialog">
      <div class="countdown-content">
        <div class="countdown-title">游戏即将开始</div>
        <div class="countdown-number">{{ countdownNumber }}</div>
        <div class="countdown-text">准备开始涂色抢地盘！</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onUnmounted } from 'vue'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  duration: {
    type: Number,
    default: 5
  }
})

const emit = defineEmits(['countdown-complete'])

const countdownNumber = ref(props.duration)
let countdownTimer = null

// 先声明函数，再使用
const startCountdown = () => {
  countdownNumber.value = props.duration
  countdownTimer = setInterval(() => {
    countdownNumber.value--
    if (countdownNumber.value <= 0) {
      stopCountdown()
      emit('countdown-complete')
    }
  }, 1000)
}

const stopCountdown = () => {
  if (countdownTimer) {
    clearInterval(countdownTimer)
    countdownTimer = null
  }
}

// 监听 visible 变化，开始倒计时
watch(() => props.visible, (newVisible) => {
  console.log('🎯 GameCountdownDialog: visible 变化:', newVisible)
  if (newVisible) {
    console.log('🎯 开始倒计时')
    startCountdown()
  } else {
    console.log('🎯 停止倒计时')
    stopCountdown()
  }
}, { immediate: true })

onUnmounted(() => {
  stopCountdown()
})
</script>

<style scoped>
.countdown-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
}

.countdown-dialog {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 20px;
  padding: 40px;
  text-align: center;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
  animation: countdown-appear 0.3s ease-out;
}

.countdown-content {
  color: white;
}

.countdown-title {
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.countdown-number {
  font-size: 120px;
  font-weight: bold;
  margin: 20px 0;
  text-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
  animation: countdown-pulse 1s ease-in-out infinite;
}

.countdown-text {
  font-size: 18px;
  opacity: 0.9;
  margin-top: 20px;
}

@keyframes countdown-appear {
  from {
    opacity: 0;
    transform: scale(0.8);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

@keyframes countdown-pulse {
  0%, 100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
}
</style>
